<template>
  <div class="admin-settings">
    <div class="page-header">
      <h2>系统设置</h2>
    </div>

    <el-row :gutter="20">
      <!-- 基本设置 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>基本设置</span>
          </template>
          <el-form :model="basicSettings" label-width="120px">
            <el-form-item label="网站名称">
              <WangEditor v-model="basicSettings.siteName" />
            </el-form-item>
            <el-form-item label="网站副标题">
              <el-input
                v-model="basicSettings.siteSubtitle"
                placeholder="如：机器人全产业链接会 2025"
              />
            </el-form-item>
            <el-form-item label="网站描述">
              <el-input
                v-model="basicSettings.siteDescription"
                type="textarea"
                :rows="3"
              />
            </el-form-item>
            <el-form-item label="网站Logo">
              <div class="image-upload-container">
                <el-upload
                  class="image-uploader"
                  :action="uploadAction"
                  :headers="uploadHeaders"
                  :data="{ type: 'logo' }"
                  :show-file-list="false"
                  :on-success="
                    (response) => handleImageSuccess(response, 'siteLogo')
                  "
                  :on-error="handleImageError"
                  :before-upload="beforeImageUpload"
                  accept="image/*"
                >
                  <img
                    v-if="basicSettings.siteLogo"
                    :src="basicSettings.siteLogo"
                    class="uploaded-image"
                  />
                  <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
                </el-upload>
                <el-input
                  v-model="basicSettings.siteLogo"
                  placeholder="或直接输入Logo URL"
                  style="margin-top: 10px"
                />
              </div>
            </el-form-item>
            <el-form-item label="版权关键词">
              <el-input
                v-model="basicSettings.siteKeywords"
                placeholder="用逗号分隔"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="saveBasicSettings"
                :loading="saving"
              >
                保存基本设置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 联系信息 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>联系信息</span>
          </template>
          <el-form :model="contactSettings" label-width="120px">
            <el-form-item label="公司名称">
              <el-input v-model="contactSettings.company" />
            </el-form-item>
            <el-form-item label="联系邮箱">
              <el-input v-model="contactSettings.email" />
            </el-form-item>
            <el-form-item label="联系电话">
              <el-input v-model="contactSettings.phone" />
            </el-form-item>
            <el-form-item label="联系地址">
              <el-input
                v-model="contactSettings.address"
                type="textarea"
                :rows="3"
              />
            </el-form-item>
            <!-- <el-form-item label="工作时间">
              <el-input v-model="contactSettings.workTime" placeholder="如：周一至周五 9:00-18:00" />
            </el-form-item> -->
            <el-form-item>
              <el-button
                type="primary"
                @click="saveContactSettings"
                :loading="saving"
              >
                保存联系信息
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px">
      <!-- 页脚基本信息设置 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>页脚基本信息设置</span>
          </template>
          <el-form :model="footerSettings" label-width="120px">
            <el-form-item label="网站名称">
              <el-input
                v-model="footerSettings.siteName"
                placeholder="如：FAIR plus"
              />
            </el-form-item>
            <el-form-item label="网站描述">
              <WangEditor v-model="footerSettings.siteDescription" />
              <!-- <el-input v-model="footerSettings.siteDescription" type="textarea" :rows="3" placeholder="网站的简短描述信息" /> -->
            </el-form-item>
            <el-form-item label="页脚Logo">
              <div class="image-upload-container">
                <el-upload
                  class="image-uploader"
                  :action="uploadAction"
                  :headers="uploadHeaders"
                  :data="{ type: 'footer-logo' }"
                  :show-file-list="false"
                  :on-success="
                    (response) => handleImageSuccess(response, 'footerLogo')
                  "
                  :on-error="handleImageError"
                  :before-upload="beforeImageUpload"
                  accept="image/*"
                >
                  <img
                    v-if="footerSettings.footerLogo"
                    :src="footerSettings.footerLogo"
                    class="uploaded-image"
                  />
                  <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
                </el-upload>
                <el-input
                  v-model="footerSettings.footerLogo"
                  placeholder="或直接输入页脚Logo URL"
                  style="margin-top: 10px"
                />
              </div>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="saveFooterSettings"
                :loading="saving"
              >
                保存页脚设置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 系统配置 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>系统配置</span>
          </template>
          <el-form :model="systemSettings" label-width="120px">
            <el-form-item label="系统维护">
              <el-switch v-model="systemSettings.maintenanceMode" />
            </el-form-item>
            <!-- <el-form-item label="注册开放">
              <el-switch v-model="systemSettings.allowRegistration" />
            </el-form-item>
            <el-form-item label="评论审核">
              <el-switch v-model="systemSettings.commentModeration" />
            </el-form-item> -->
            <el-form-item label="邮件通知">
              <el-switch v-model="systemSettings.emailNotification" />
            </el-form-item>
            <el-form-item label="缓存清理">
              <el-button type="warning" @click="clearCache">清理缓存</el-button>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="saveSystemSettings"
                :loading="saving"
              >
                保存系统配置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px">
      <!-- 页脚链接配置 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>页脚链接配置</span>
          </template>
          <el-tabs v-model="activeFooterTab" type="card">
            <el-tab-pane label="快速链接" name="quickLinks">
              <div class="footer-links-container">
                <div
                  v-for="(link, index) in footerLinks.quickLinks"
                  :key="index"
                  class="link-item"
                >
                  <el-input
                    v-model="link.description"
                    placeholder="链接名称"
                    style="width: 200px; margin-right: 10px"
                  />
                  <el-input
                    v-model="link.settingValue"
                    placeholder="链接地址"
                    style="width: 200px; margin-right: 10px"
                  />
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeQuickLink(index)"
                    >删除</el-button
                  >
                </div>
                <el-button
                  type="primary"
                  size="small"
                  @click="addQuickLink"
                  style="margin-top: 10px"
                >
                  添加快速链接
                </el-button>
              </div>
            </el-tab-pane>
            <el-tab-pane label="展会信息" name="exhibitionLinks">
              <div class="footer-links-container">
                <div
                  v-for="(link, index) in footerLinks.exhibitionLinks"
                  :key="index"
                  class="link-item"
                >
                  <el-input
                    v-model="link.description"
                    placeholder="链接名称"
                    style="width: 200px; margin-right: 10px"
                  />
                  <el-input
                    v-model="link.settingValue"
                    placeholder="链接地址"
                    style="width: 200px; margin-right: 10px"
                  />
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeExhibitionLink(index)"
                    >删除</el-button
                  >
                </div>
                <el-button
                  type="primary"
                  size="small"
                  @click="addExhibitionLink"
                  style="margin-top: 10px"
                >
                  添加展会信息链接
                </el-button>
              </div>
            </el-tab-pane>
          </el-tabs>
          <el-button
            type="primary"
            @click="saveFooterLinks"
            :loading="saving"
            style="margin-top: 20px"
          >
            保存页脚链接配置
          </el-button>
        </el-card>
      </el-col>

      <!-- 备案链接设置 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>备案链接设置</span>
          </template>
          <div class="footer-links-container">
            <div
              v-for="(item, index) in recordLinks"
              :key="item.key || index"
              class="link-item"
            >
              <el-input
                v-model="item.text"
                placeholder="备案名称，如：粤ICP备xxxxxxx号"
                style="width: 220px; margin-right: 10px"
              />
              <el-input
                v-model="item.url"
                placeholder="备案跳转链接，如：https://beian.miit.gov.cn"
                style="width: 260px; margin-right: 10px"
              />
              <el-button
                type="danger"
                size="small"
                @click="removeRecordLink(index)"
                >删除</el-button
              >
            </div>
            <el-button
              type="primary"
              size="small"
              @click="addRecordLink"
              style="margin-top: 10px"
              >添加备案链接</el-button
            >
          </div>
          <el-button
            type="primary"
            @click="saveRecordLinks"
            :loading="saving"
            style="margin-top: 20px"
          >
            保存备案链接设置
          </el-button>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px">

      <!-- 法律文档配置（富文本） -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>参观与底部条款配置</span>
          </template>
          <el-tabs v-model="activeVisitorLegalTab" type="card">
            <el-tab-pane label="参观条款" name="visitorTerms">
              <WangEditor v-model="visitorTerms.content" />
              <div style="margin-top: 12px; text-align: right">
                <el-button
                  type="primary"
                  @click="saveVisitorTerms"
                  :loading="saving"
                >
                  保存参观条款
                </el-button>
              </div>
            </el-tab-pane>
            <el-tab-pane label="参观隐私政策" name="visitorPrivacy">
              <WangEditor v-model="visitorPrivacyPolicy.content" />
              <div style="margin-top: 12px; text-align: right">
                <el-button
                  type="primary"
                  @click="saveVisitorPrivacyPolicy"
                  :loading="saving"
                >
                  保存参观隐私政策
                </el-button>
              </div>
            </el-tab-pane>
            <el-tab-pane label="底部隐私政策" name="footerPrivacy">
              <WangEditor v-model="footerPrivacyPolicy.content" />
              <div style="margin-top: 12px; text-align: right">
                <el-button
                  type="primary"
                  @click="saveFooterPrivacyPolicy"
                  :loading="saving"
                >
                  保存底部隐私政策
                </el-button>
              </div>
            </el-tab-pane>
            <el-tab-pane label="底部服务条款" name="footerTerms">
              <WangEditor v-model="footerTermsOfService.content" />
              <div style="margin-top: 12px; text-align: right">
                <el-button
                  type="primary"
                  @click="saveFooterTermsOfService"
                  :loading="saving"
                >
                  保存底部服务条款
                </el-button>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import WangEditor from "@/components/WangEditor.vue";
import { systemApi } from "@/api/admin";
import config from "@/config";

export default {
  name: "AdminSettings",
  components: {
    Plus,
    WangEditor,
  },
  setup() {
    const saving = ref(false);

    // 基本设置
    const basicSettings = reactive({
      siteName: "",
      siteSubtitle: "",
      siteDescription: "",
      siteLogo: "",
      siteKeywords: "",
    });

    // 联系信息
    const contactSettings = reactive({
      company: "",
      phone: "",
      email: "",
      address: "",
      workTime: "",
    });

    // 页脚基本信息设置
    const footerSettings = reactive({
      siteName: "",
      siteDescription: "",
      footerLogo: "",
    });

    // 系统配置
    const systemSettings = reactive({
      maintenanceMode: false,
      allowRegistration: true,
      commentModeration: true,
      emailNotification: true,
    });

    // 页脚链接配置
    const footerLinks = reactive({
      quickLinks: [],
      exhibitionLinks: [],
    });

    // 备案链接配置（数组：{ text, url, key }）
    const recordLinks = ref([]);

    // 法律文档配置（链接 + 富文本）
    const privacyPolicy = reactive({
      content: "",
    });

    const termsOfService = reactive({
      content: "",
    });

    const visitorTerms = reactive({
      content: "",
    });

    const visitorPrivacyPolicy = reactive({
      content: "",
    });

    const footerPrivacyPolicy = reactive({
      content: "",
    });

    const footerTermsOfService = reactive({
      content: "",
    });

    // 标签页状态
    const activeFooterTab = ref("quickLinks");
    const activeLegalTab = ref("privacy");
    const activeVisitorLegalTab = ref("visitorTerms");

    // 加载系统设置
    const loadSettings = async () => {
      try {
        const response = await systemApi.getAllSettings();
        if (response.code === "200") {
          const settings = response.data || [];
          const settingsMap = {};
          settings.forEach((setting) => {
            settingsMap[setting.settingKey] = setting.settingValue;
          });

          // 更新基本设置
          basicSettings.siteName =
            settingsMap.site_name || basicSettings.siteName;
          basicSettings.siteSubtitle =
            settingsMap.site_subtitle || basicSettings.siteSubtitle;
          basicSettings.siteDescription =
            settingsMap.site_description || basicSettings.siteDescription;
          basicSettings.siteLogo =
            settingsMap.site_logo || basicSettings.siteLogo;
          basicSettings.siteKeywords =
            settingsMap.site_keywords || basicSettings.siteKeywords;

          // 更新联系信息
          contactSettings.company =
            settingsMap["contact.company"] ||
            settingsMap.contact_company ||
            contactSettings.company;
          contactSettings.phone =
            settingsMap.contact_phone || contactSettings.phone;
          contactSettings.email =
            settingsMap.contact_email || contactSettings.email;
          contactSettings.address =
            settingsMap.contact_address || contactSettings.address;
          contactSettings.workTime =
            settingsMap.work_time || contactSettings.workTime;

          // 备案链接
          try {
            recordLinks.value = settingsMap.record_links
              ? JSON.parse(settingsMap.record_links)
              : [];
          } catch {
            recordLinks.value = [];
          }

          // 更新系统配置
          systemSettings.maintenanceMode =
            settingsMap.maintenance_mode === "true";
          systemSettings.allowRegistration =
            settingsMap.allow_registration === "true";
          systemSettings.commentModeration =
            settingsMap.comment_moderation === "true";
          systemSettings.emailNotification =
            settingsMap.email_notification === "true";

          // 更新页脚基本信息设置
          footerSettings.siteName =
            settingsMap["footer.site_name"] || footerSettings.siteName;
          footerSettings.siteDescription =
            settingsMap["footer.site_description"] ||
            footerSettings.siteDescription;
          footerSettings.footerLogo =
            settingsMap["footer.logo"] || footerSettings.footerLogo;
        }

        // 加载页脚链接配置（只在首次加载时）
        if (
          footerLinks.quickLinks.length === 0 &&
          footerLinks.exhibitionLinks.length === 0
        ) {
          await loadFooterLinks();
        }

        // 法律文档的加载改为在 onMounted 中统一触发，避免条件不足时不请求
      } catch (error) {
        console.error("加载系统设置失败:", error);
      }
    };

    // 保存备案链接设置
    const saveRecordLinks = async () => {
      saving.value = true;
      try {
        const cleaned = recordLinks.value
          .filter((it) => it && (it.text?.trim() || it.url?.trim()))
          .map((it) => ({
            text: (it.text || "").trim(),
            url: (it.url || "").trim(),
            key:
              it.key ||
              `record_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
          }));
        await systemApi.updateSetting({
          settingKey: "record_links",
          settingValue: JSON.stringify(cleaned),
          settingType: "json",
          description: "备案链接设置",
          groupName: "footer",
          isPublic: true,
        });
        ElMessage.success("备案链接设置保存成功");
        await loadSettings();
      } catch (e) {
        ElMessage.error("保存失败");
      } finally {
        saving.value = false;
      }
    };

    // 备案链接本地增删
    const addRecordLink = () => {
      recordLinks.value.push({
        text: "",
        url: "",
        key: `record_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      });
    };
    const removeRecordLink = (index) => {
      recordLinks.value.splice(index, 1);
    };

    // 保存基本设置
    const saveBasicSettings = async () => {
      saving.value = true;
      try {
        const settings = [
          {
            settingKey: "site_name",
            settingValue: basicSettings.siteName,
            settingType: "string",
            description: "网站名称",
            groupName: "basic",
            isPublic: true,
          },
          {
            settingKey: "site_subtitle",
            settingValue: basicSettings.siteSubtitle,
            settingType: "string",
            description: "网站副标题",
            groupName: "basic",
            isPublic: true,
          },
          {
            settingKey: "site_description",
            settingValue: basicSettings.siteDescription,
            settingType: "string",
            description: "网站描述",
            groupName: "basic",
            isPublic: true,
          },
          {
            settingKey: "site_logo",
            settingValue: basicSettings.siteLogo,
            settingType: "string",
            description: "网站Logo",
            groupName: "basic",
            isPublic: true,
          },
          {
            settingKey: "site_keywords",
            settingValue: basicSettings.siteKeywords,
            settingType: "string",
            description: "网站关键词",
            groupName: "basic",
            isPublic: true,
          },
        ];

        for (const setting of settings) {
          await systemApi.updateSetting(setting);
        }

        ElMessage.success("基本设置保存成功");
        // 重新加载设置数据
        await loadSettings();
      } catch (error) {
        ElMessage.error("保存失败");
      } finally {
        saving.value = false;
      }
    };

    // 保存联系信息
    const saveContactSettings = async () => {
      saving.value = true;
      try {
        const settings = [
          {
            settingKey: "contact.company",
            settingValue: contactSettings.company,
            settingType: "string",
            description: "公司名称",
            groupName: "contact",
            isPublic: true,
          },
          {
            settingKey: "contact_phone",
            settingValue: contactSettings.phone,
            settingType: "string",
            description: "联系电话",
            groupName: "contact",
            isPublic: true,
          },
          {
            settingKey: "contact_email",
            settingValue: contactSettings.email,
            settingType: "string",
            description: "联系邮箱",
            groupName: "contact",
            isPublic: true,
          },
          {
            settingKey: "contact_address",
            settingValue: contactSettings.address,
            settingType: "string",
            description: "联系地址",
            groupName: "contact",
            isPublic: true,
          },
          {
            settingKey: "work_time",
            settingValue: contactSettings.workTime,
            settingType: "string",
            description: "工作时间",
            groupName: "contact",
            isPublic: true,
          },
        ];

        for (const setting of settings) {
          await systemApi.updateSetting(setting);
        }

        ElMessage.success("联系信息保存成功");
        // 重新加载设置数据
        await loadSettings();
      } catch (error) {
        ElMessage.error("保存失败");
      } finally {
        saving.value = false;
      }
    };

    // 保存页脚基本信息设置
    const saveFooterSettings = async () => {
      saving.value = true;
      try {
        const settings = [
          {
            settingKey: "footer.site_name",
            settingValue: footerSettings.siteName,
            settingType: "string",
            description: "页脚网站名称",
            groupName: "footer",
            isPublic: true,
          },
          {
            settingKey: "footer.site_description",
            settingValue: footerSettings.siteDescription,
            settingType: "string",
            description: "页脚网站描述",
            groupName: "footer",
            isPublic: true,
          },
          {
            settingKey: "footer.logo",
            settingValue: footerSettings.footerLogo,
            settingType: "string",
            description: "页脚Logo",
            groupName: "footer",
            isPublic: true,
          },
        ];

        for (const setting of settings) {
          await systemApi.updateSetting(setting);
        }

        ElMessage.success("页脚设置保存成功");
        // 重新加载设置数据
        await loadSettings();
      } catch (error) {
        ElMessage.error("保存失败");
      } finally {
        saving.value = false;
      }
    };

    // 保存系统配置
    const saveSystemSettings = async () => {
      saving.value = true;
      try {
        const settings = [
          {
            settingKey: "maintenance_mode",
            settingValue: systemSettings.maintenanceMode.toString(),
            settingType: "boolean",
            description: "维护模式",
            groupName: "system",
            isPublic: false,
          },
          // {
          //   settingKey: 'allow_registration',
          //   settingValue: systemSettings.allowRegistration.toString(),
          //   settingType: 'boolean',
          //   description: '允许注册',
          //   groupName: 'system',
          //   isPublic: false
          // },
          // {
          //   settingKey: 'comment_moderation',
          //   settingValue: systemSettings.commentModeration.toString(),
          //   settingType: 'boolean',
          //   description: '评论审核',
          //   groupName: 'system',
          //   isPublic: false
          // },
          {
            settingKey: "email_notification",
            settingValue: systemSettings.emailNotification.toString(),
            settingType: "boolean",
            description: "邮件通知",
            groupName: "system",
            isPublic: false,
          },
        ];

        for (const setting of settings) {
          await systemApi.updateSetting(setting);
        }

        ElMessage.success("系统配置保存成功");
        // 重新加载设置数据
        await loadSettings();
      } catch (error) {
        ElMessage.error("保存失败");
      } finally {
        saving.value = false;
      }
    };

    // 清理缓存
    const clearCache = async () => {
      try {
        await ElMessageBox.confirm(
          "确定要清理系统缓存吗？这可能会影响系统性能。",
          "确认清理",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );

        // 模拟清理缓存
        await new Promise((resolve) => setTimeout(resolve, 2000));
        ElMessage.success("缓存清理成功");
      } catch {
        // 用户取消
      }
    };

    // 加载页脚链接配置
    const loadFooterLinks = async () => {
      try {
        const response = await systemApi.getFooterLinks();
        if (response.code === "200") {
          footerLinks.quickLinks = response.data.quickLinks || [];
          footerLinks.exhibitionLinks = response.data.exhibitionLinks || [];
        }
      } catch (error) {
        console.error("加载页脚链接配置失败:", error);
      }
    };

    // 加载法律文档（链接 + 富文本内容）
    const loadLegalDocuments = async () => {
      try {
        const [
          privacyResponse,
          termsResponse,
          visitorTermsResponse,
          visitorPrivacyResponse,
          footerPrivacyResponse,
          footerTermsResponse,
        ] = await Promise.all([
          systemApi.getPrivacyPolicy(),
          systemApi.getTermsOfService(),
          systemApi.getVisitorTerms(),
          systemApi.getVisitorPrivacyPolicy(),
          systemApi.getFooterPrivacyPolicy(),
          systemApi.getFooterTermsOfService(),
        ]);

        if (privacyResponse.code === "200") {
          privacyPolicy.content = privacyResponse.data?.settingValue || "";
        }

        if (termsResponse.code === "200") {
          termsOfService.content = termsResponse.data?.settingValue || "";
        }

        if (visitorTermsResponse.code === "200") {
          visitorTerms.content = visitorTermsResponse.data?.settingValue || "";
        }

        if (visitorPrivacyResponse.code === "200") {
          visitorPrivacyPolicy.content =
            visitorPrivacyResponse.data?.settingValue || "";
        }

        if (footerPrivacyResponse.code === "200") {
          footerPrivacyPolicy.content =
            footerPrivacyResponse.data?.settingValue || "";
        }

        if (footerTermsResponse.code === "200") {
          footerTermsOfService.content =
            footerTermsResponse.data?.settingValue || "";
        }
      } catch (error) {
        console.error("加载法律文档失败:", error);
      }
    };

    // 添加快速链接
    const addQuickLink = () => {
      footerLinks.quickLinks.push({
        description: "",
        settingValue: "",
        key: `quick_link_${Date.now()}_${Math.random()
          .toString(36)
          .substr(2, 9)}`,
      });
    };

    // 删除快速链接
    const removeQuickLink = (index) => {
      footerLinks.quickLinks.splice(index, 1);
    };

    // 添加展会信息链接
    const addExhibitionLink = () => {
      footerLinks.exhibitionLinks.push({
        description: "",
        settingValue: "",
        key: `exhibition_link_${Date.now()}_${Math.random()
          .toString(36)
          .substr(2, 9)}`,
      });
    };

    // 删除展会信息链接
    const removeExhibitionLink = (index) => {
      footerLinks.exhibitionLinks.splice(index, 1);
    };

    // 保存页脚链接配置
    const saveFooterLinks = async () => {
      saving.value = true;
      try {
        // 过滤掉空的链接
        const validQuickLinks = footerLinks.quickLinks
          .filter(
            (link) => link.settingValue && link.settingValue.trim() !== ""
          )
          .map((link, index) => ({
            key:
              link.key ||
              `quick_link_${Date.now()}_${index}_${Math.random()
                .toString(36)
                .substr(2, 9)}`,
            value: link.settingValue.trim(),
            description: link.description || "",
          }));

        const validExhibitionLinks = footerLinks.exhibitionLinks
          .filter(
            (link) => link.settingValue && link.settingValue.trim() !== ""
          )
          .map((link, index) => ({
            key:
              link.key ||
              `exhibition_link_${Date.now()}_${index}_${Math.random()
                .toString(36)
                .substr(2, 9)}`,
            value: link.settingValue.trim(),
            description: link.description || "",
          }));

        const data = {
          quickLinks: validQuickLinks,
          exhibitionLinks: validExhibitionLinks,
        };

        await systemApi.updateFooterLinks(data);
        ElMessage.success("页脚链接配置保存成功");
        await loadFooterLinks();
      } catch (error) {
        console.error("保存页脚链接失败:", error);
        ElMessage.error("保存失败");
      } finally {
        saving.value = false;
      }
    };

    // 保存隐私政策（保存为链接字符串）
    const savePrivacyPolicy = async () => {
      saving.value = true;
      try {
        await systemApi.updatePrivacyPolicy({ content: privacyPolicy.content });
        ElMessage.success("隐私政策保存成功");
      } catch (error) {
        ElMessage.error("保存失败");
      } finally {
        saving.value = false;
      }
    };

    // 保存服务条款（保存为链接字符串）
    const saveTermsOfService = async () => {
      saving.value = true;
      try {
        await systemApi.updateTermsOfService({
          content: termsOfService.content,
        });
        ElMessage.success("服务条款保存成功");
      } catch (error) {
        ElMessage.error("保存失败");
      } finally {
        saving.value = false;
      }
    };

    // 保存参观条款
    const saveVisitorTerms = async () => {
      saving.value = true;
      try {
        await systemApi.updateVisitorTerms({ content: visitorTerms.content });
        ElMessage.success("参观条款保存成功");
      } catch (error) {
        ElMessage.error("保存失败");
      } finally {
        saving.value = false;
      }
    };

    // 保存参观隐私政策
    const saveVisitorPrivacyPolicy = async () => {
      saving.value = true;
      try {
        await systemApi.updateVisitorPrivacyPolicy({
          content: visitorPrivacyPolicy.content,
        });
        ElMessage.success("参观隐私政策保存成功");
      } catch (error) {
        ElMessage.error("保存失败");
      } finally {
        saving.value = false;
      }
    };

    // 保存底部隐私政策
    const saveFooterPrivacyPolicy = async () => {
      saving.value = true;
      try {
        await systemApi.updateFooterPrivacyPolicy({
          content: footerPrivacyPolicy.content,
        });
        ElMessage.success("底部隐私政策保存成功");
      } catch (error) {
        ElMessage.error("保存失败");
      } finally {
        saving.value = false;
      }
    };

    // 保存底部服务条款
    const saveFooterTermsOfService = async () => {
      saving.value = true;
      try {
        await systemApi.updateFooterTermsOfService({
          content: footerTermsOfService.content,
        });
        ElMessage.success("底部服务条款保存成功");
      } catch (error) {
        ElMessage.error("保存失败");
      } finally {
        saving.value = false;
      }
    };

    // 上传相关配置
    const apiConfig = config.getApiConfig();
    const uploadAction = ref(`${apiConfig.baseURL}/api/upload/image`);
    const uploadHeaders = ref({
      token: localStorage.getItem("adminToken") || "",
    });

    // 图片上传成功处理
    const handleImageSuccess = (response, field) => {
      if (response && (response.code === "200" || response.code === 200)) {
        if (field === "footerLogo") {
          footerSettings[field] = response.data.url;
        } else {
          basicSettings[field] = response.data.url;
        }
        ElMessage.success("图片上传成功!");
      } else {
        ElMessage.error("图片上传失败!");
      }
    };

    // 图片上传错误处理
    const handleImageError = (error) => {
      console.error("图片上传失败:", error);
      ElMessage.error("图片上传失败，请重试!");
    };

    // 图片上传前验证
    const beforeImageUpload = (file) => {
      const isImage = file.type.startsWith("image/");
      const isLt2M = file.size / 1024 / 1024 < 15;

      if (!isImage) {
        ElMessage.error("只能上传图片文件!");
        return false;
      }
      if (!isLt2M) {
        ElMessage.error("图片大小不能超过 15MB!");
        return false;
      }
      return true;
    };

    onMounted(async () => {
      // 初始化时同时加载系统设置和法律文档
      await loadSettings();
      await loadLegalDocuments();
    });

    return {
      saving,
      basicSettings,
      contactSettings,
      footerSettings,
      systemSettings,
      footerLinks,
      recordLinks,
      privacyPolicy,
      termsOfService,
      visitorTerms,
      visitorPrivacyPolicy,
      footerPrivacyPolicy,
      footerTermsOfService,
      activeFooterTab,
      activeLegalTab,
      activeVisitorLegalTab,
      loadSettings,
      // 保存/增删 备案
      saveRecordLinks,
      addRecordLink,
      removeRecordLink,
      // 其余
      saveBasicSettings,
      saveContactSettings,
      saveFooterSettings,
      saveSystemSettings,
      clearCache,
      loadFooterLinks,
      loadLegalDocuments,
      saveFooterLinks,
      savePrivacyPolicy,
      saveTermsOfService,
      saveVisitorTerms,
      saveVisitorPrivacyPolicy,
      saveFooterPrivacyPolicy,
      saveFooterTermsOfService,
      uploadAction,
      uploadHeaders,
      handleImageSuccess,
      handleImageError,
      beforeImageUpload,
      addQuickLink,
      removeQuickLink,
      addExhibitionLink,
      removeExhibitionLink,
    };
  },
};
</script>

<style scoped>
.admin-settings {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
}

/* Logo上传样式 */
.image-upload-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  width: 120px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-uploader:hover {
  border-color: #409eff;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 4px;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.footer-links-container {
  min-height: 200px;
}

.link-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fafafa;
}

.link-item:hover {
  background-color: #f5f7fa;
}
</style>
